﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using MvcEngine.Core.Website;
using MvcEngine.Core;
using MvcEngine.Core.Extensions;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Core.Account;
using MvcEngine.Core.Localization;
using MvcEngine.Mvc.Models;
using MvcEngine.Core.Helpers;

namespace MvcEngine.Mvc.ModelBinders
{
    public class LoginModelBinder : ModelBinderBase
    {
        public override object Bind(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;
            LoginViewModel model = new LoginViewModel();

            model.Email = request.Form.Get("Email");
            model.Password = request.Form.Get("Password");
            model.RememberMe = GetBool(request.Form.Get("RememberMe"));
            
            Validate(model, controllerContext);

            if (bindingContext.ModelState.IsValid)
                ValidateLogOn(model, bindingContext);
            return model;
        }

        protected virtual void ValidateLogOn(LoginViewModel item, ModelBindingContext bindingContext)
        {
            if (!ValidateUser(item.Email, item.Password))
            {
                bindingContext.ModelState.AddModelError("Email", ResourceReader.Current.GetString("IncorrectPasswordOrEmail"));
            }

            if (bindingContext.ModelState.IsValid)
            {
                User user = AccountManager.Current.GetUser(item.Email);
                if (!user.IsApproved)
                {
                    bindingContext.ModelState.AddModelError("Email", ResourceReader.Current.GetString("UserIsNotActivated"));
                }
                if (user.IsLockedOut)
                {
                    bindingContext.ModelState.AddModelError("Email", ResourceReader.Current.GetString("UserIsLocked"));
                }
            }
        }

        private bool ValidateUser(string email, string password)
        {
            User user = AccountManager.Current.GetUser(email);
            if (user == null)
                return false;
            return HashHelper.Current.VerifyHash(password, user.Password, user.PasswordSalt);
        }
    }
}
